/**
 * 2024/01/01 - 2024/12/31
 **/
package com.snail.starter.utils.queue.producer;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.function.Supplier;

/**
 * @author: (zg)
 * @Date: 2024/6/3 10:33
 * @Version: 1.0.0
 */
@Slf4j
public class QueueProducer<T> extends Thread {

    private final ArrayBlockingQueue<T> blockingQueue;

    private final Supplier<List<T>> supplier;

    private final long sleepTime;

    private volatile boolean isRunning = true;

    public QueueProducer(ArrayBlockingQueue<T> blockingQueue, Supplier<List<T>> supplier) {
        this.blockingQueue = blockingQueue;
        this.supplier = supplier;
        this.sleepTime = 1000L;
    }

    public QueueProducer(ArrayBlockingQueue<T> blockingQueue, Supplier<List<T>> supplier, long sleepTime) {
        this.blockingQueue = blockingQueue;
        this.supplier = supplier;
        this.sleepTime = sleepTime;
    }

    @Override
    public void run() {
        while (isRunning) {
            if (putBeforeIsSleep()) {
                continue;
            }
            List<T> ts = supplier.get();
            if (null != ts && !ts.isEmpty()) {
                for (T t : ts) {
                    pushQueue(t);
                }
            }
        }
    }

    private boolean putBeforeIsSleep() {
        if (blockingQueue.size() > 400) {
            try {
                log.info("=========================== producer sleep ===========================");
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                log.warn("Producer before InterruptedException");
            }
            return true;
        }
        return false;
    }

    private void pushQueue(T t) {
        try {
            blockingQueue.put(t);
        } catch (InterruptedException interruptedException) {
            log.warn("", interruptedException);
            log.warn("Producer put queue InterruptedException, t:{}", t);
        } catch (Throwable throwable) {
            log.warn("", throwable);
            log.warn("Producer put queue throwable, t:{}", t);
        }
    }

    public void stopProducer() {
        this.isRunning = false;
    }
}